package com.anos.smsfun.fragment;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.anos.smsfun.R;
import com.anos.smsfun.activities.NewMessagingActivity;
import com.anos.smsfun.activities.ViewSmsConversationActivity;
import com.anos.smsfun.adapter.ConversationListAdapter;
import com.anos.smsfun.cache.SMSFunDataCache;
import com.anos.smsfun.controller.DataRequestCallback;
import com.anos.smsfun.model.MessageItem;
import com.anos.smsfun.task.DoingBackground;
import com.anos.smsfun.task.QueryUtils;
import com.anos.smsfun.utility.DefConstants;

public class SMSFragment extends LoadingStateFragment implements
		OnItemClickListener, OnClickListener, OnItemLongClickListener {

	private ListView mListView;
	private ImageButton btnCreateNewMSG;
	private ImageButton btnDeleteMSG;
	private ImageButton btnCancelDeleteMSG;
	private TextView tvNumDelete;
	private LinearLayout l_layoutCancel;

	private ArrayList<MessageItem> mMessageItems = new ArrayList<MessageItem>();
	private ArrayList<MessageItem> mMessageItemsDelete = new ArrayList<MessageItem>();
	private ConversationListAdapter mConversationAdapter;
	private SMSFunDataCache mSmsFunDataCache;

	private Activity mActivity;

	private boolean mIsListLoading = false;

	/**
	 * Cờ này bật lên khi long click vào item msg để xoá item, khi cờ đang bật
	 * nếu click vào item khác sẽ thêm vào list delete
	 */
	private boolean mIsLongClickToDelete = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mActivity = getActivity();
		mSmsFunDataCache = SMSFunDataCache.getInstance(mActivity);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_sms, container, false);
		// find view id
		findViewByIdAll(view);

		// if (mMessageItems != null && mMessageItems.size() > 0) {
		// mConversationAdapter = new ConversationListAdapter(mActivity,
		// mMessageItems);
		// mListView.setAdapter(mConversationAdapter);
		// } else {
		// getMessageItemList();
		// }

		return view;
	}

	@SuppressWarnings("static-access")
	@Override
	public void onResume() {
		// get list data
		getMessageItemList();
		// clear notification
		NotificationManager notificationManager = (NotificationManager) mActivity
				.getSystemService(mActivity.NOTIFICATION_SERVICE);
		notificationManager.cancel(DefConstants.ID_NOTIFICATION_RECEIVED);

		super.onResume();
	}

	private void findViewByIdAll(View view) {
		mListView = (ListView) view.findViewById(R.id.lvConversationList);
		btnCreateNewMSG = (ImageButton) view
				.findViewById(R.id.btnCreateNewMSG_frSMS);
		btnDeleteMSG = (ImageButton) view.findViewById(R.id.btnDelete_frSMS);

		l_layoutCancel = (LinearLayout) view
				.findViewById(R.id.layout_cancel_frSMS);
		btnCancelDeleteMSG = (ImageButton) view
				.findViewById(R.id.btnCancelDelete_frSMS);
		tvNumDelete = (TextView) view.findViewById(R.id.tvNumItemDelete_frSMS);
		l_layoutCancel.setVisibility(View.GONE);

		btnDeleteMSG.setVisibility(View.GONE);

		mListView.setFastScrollEnabled(true);
		mListView.setOnItemClickListener(this);
		mListView.setOnItemLongClickListener(this);

		btnCreateNewMSG.setOnClickListener(this);
		btnDeleteMSG.setOnClickListener(this);
		btnCancelDeleteMSG.setOnClickListener(this);
	}

	@Override
	public boolean isLoading() {
		return mIsListLoading;
	}

	@Override
	public void onDestroy() {
		mMessageItems.clear();
		mMessageItemsDelete.clear();
		super.onDestroy();
	}

	/**
	 * get message list
	 * 
	 */
	private void getMessageItemList() {
		mIsListLoading = true;
		mMessageItems.clear();
		mMessageItemsDelete.clear();
		DoingBackground.readAllSMS(mActivity, onDataListResult);
	}

	private DataRequestCallback<ArrayList<MessageItem>> onDataListResult = new DataRequestCallback<ArrayList<MessageItem>>() {

		@Override
		public void onResult(ArrayList<MessageItem> result,
				boolean continueWaiting) {
			Context c = mActivity;
			if (c == null) {
				return;
			}

			if (result != null && !result.isEmpty()) {
				// get name display
				for (MessageItem msgItem : result) {
					try {
						msgItem.setNameDisplay(mSmsFunDataCache
								.getContactDetail(msgItem.getAddress())
								.getDisplayName());
					} catch (Exception e) {
					}
				}
				mMessageItems.addAll(result);

				mConversationAdapter = new ConversationListAdapter(mActivity,
						mMessageItems);
				mListView.setAdapter(mConversationAdapter);
			} else {
				if (!continueWaiting) {
					// Có lỗi xảy ra khi request dữ liệu
					Toast.makeText(c, R.string.loading_msg_error_toast,
							Toast.LENGTH_LONG).show();
				}
			}

			// cap nhat trang thai load data
			mIsListLoading = continueWaiting;
		}
	};

	@Override
	public void onItemClick(AdapterView<?> av, View v, int position, long id) {
		final MessageItem messageItem = mMessageItems.get(position);
		if (messageItem != null) {
			if (!mIsLongClickToDelete) {
				Intent intent = new Intent(mActivity,
						ViewSmsConversationActivity.class);
				intent.putExtra(DefConstants.ACTION_VIEW_CONVERSATION,
						messageItem.getAddress());
				mActivity.startActivity(intent);
				mActivity.overridePendingTransition(0, R.anim.exit_slide_left);
			} else {
				if (mMessageItemsDelete.contains(messageItem)) {
					mMessageItemsDelete.remove(messageItem);
					// v.setBackgroundColor(Color.WHITE);
					messageItem.setSelected(false);
				} else {
					btnDeleteMSG.setVisibility(View.VISIBLE);
					mMessageItemsDelete.add(messageItem);
					// v.setBackgroundColor(Color.GRAY);
					messageItem.setSelected(true);
				}

				hideViewCancelDelete();
			}
		}
	}

	/**
	 * cập nhật lại giao diện khi chọn item để xoá...
	 */
	private void hideViewCancelDelete() {
		if (mMessageItemsDelete.size() == 0) {
			l_layoutCancel.setVisibility(View.GONE);
			btnDeleteMSG.setVisibility(View.GONE);
			btnCreateNewMSG.setVisibility(View.VISIBLE);
			mIsLongClickToDelete = false;

			for (MessageItem item : mMessageItems) {
				item.setSelected(false);
			}
		} else {
			l_layoutCancel.setVisibility(View.VISIBLE);
			btnDeleteMSG.setVisibility(View.VISIBLE);
			btnCreateNewMSG.setVisibility(View.GONE);
			mIsLongClickToDelete = true;
		}
		mConversationAdapter.notifyDataSetChanged();
		tvNumDelete.setText(mMessageItemsDelete.size() + "");
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnCreateNewMSG_frSMS:
			Intent intent = new Intent(mActivity,
					NewMessagingActivity.class);
			intent.putExtra(DefConstants.ACTION_VIEW_FIND_CONTACT, "");
			mActivity.startActivity(intent);
			mActivity.overridePendingTransition(0, R.anim.exit_slide_left);
			break;

		case R.id.btnCancelDelete_frSMS:
			mMessageItemsDelete.clear();
			hideViewCancelDelete();
			break;

		case R.id.btnDelete_frSMS:
			if (mIsLongClickToDelete && mMessageItemsDelete.size() > 0) {
				Builder builder = new Builder(mActivity);
				builder.setTitle("Xoá");
				builder.setMessage(mMessageItemsDelete.size()
						+ " cuộc trò chuyện sẽ bị xoá ?");
				builder.setPositiveButton(mActivity.getString(R.string.ok),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// delete
								deleteListConversation();
							}
						});
				builder.setNegativeButton(mActivity.getString(R.string.cancel),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();

								mMessageItemsDelete.clear();
								hideViewCancelDelete();
							}
						});
				AlertDialog alertDialog = builder.create();
				alertDialog.show();

			}
			break;

		default:
			break;
		}
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> av, View v, int position,
			long id) {
		MessageItem messageItem = mMessageItems.get(position);
		if (messageItem != null) {
			if (mMessageItemsDelete.contains(messageItem)) {
				mMessageItemsDelete.remove(messageItem);
				// v.setBackgroundColor(Color.WHITE);
				messageItem.setSelected(false);
			} else {
				btnDeleteMSG.setVisibility(View.VISIBLE);
				mMessageItemsDelete.add(messageItem);
				// v.setBackgroundColor(Color.GRAY);
				messageItem.setSelected(true);
			}
		}
		hideViewCancelDelete();

		return true;
	}

	/**
	 * xoá danh sách cuộc trò chuyện
	 */
	private void deleteListConversation() {
		try {
			for (MessageItem msg : mMessageItemsDelete) {
				QueryUtils.deleteConvsersation(mActivity, msg.getThreadId());
			}
			// update lai list
			getMessageItemList();

			hideViewCancelDelete();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
